package com.fly.show.git;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class GitService
{
    @Value("${git.url:}")
    private String url;
    
    private Git git;
    
    File project = new File("project/");
    
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    
    /**
     * git目录初始化
     */
    public void init()
    {
        try
        {
            if (SystemUtils.IS_OS_UNIX)
            {
                // 克隆远程库
                FileUtils.deleteQuietly(project);
                log.info("### git init for {}", url);
                git = Git.cloneRepository().setURI(url).setBranch("master").setDirectory(project).call();
            }
        }
        catch (GitAPIException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    /**
     * 获取子项目目录名
     */
    public List<String> getSubNames()
    {
        if (!project.exists())
        {
            return Collections.emptyList();
        }
        List<String> subNames = Stream.of(project.listFiles()).filter(File::isDirectory).filter(file -> !file.isHidden()).map(file -> file.getName()).sorted().collect(Collectors.toList());
        
        // 添加2级子项目名
        try
        {
            subNames.addAll(Stream.of(resolver.getResources("file:" + project.getCanonicalPath() + "/*/*/pom.xml")) // 2级子目录
                .map(r -> StringUtils.substringBetween(r.getDescription(), "project/", "/pom.xml"))
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList()));
            Collections.sort(subNames);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
        return subNames;
    }
    
    /**
     * 模糊查找子项目
     */
    public List<String> search(String name)
    {
        return getSubNames().stream().filter(t -> StringUtils.containsIgnoreCase(t, name)).collect(Collectors.toList());
    }
    
    /**
     * 优先精确查找、模糊查找子项目
     */
    public List<String> getSubNames(String name)
    {
        // 精确查找
        if (new File("project/" + name).exists())
        {
            return Collections.singletonList(name);
        }
        return getSubNames().stream().filter(t -> StringUtils.containsIgnoreCase(t, name)).collect(Collectors.toList());
    }
    
    /**
     * 拉取远程仓库内容到本地
     */
    public void pull()
    {
        try
        {
            if (SystemUtils.IS_OS_UNIX)
            {
                log.info("### git pull for {}", url);
                git.pull().setRemote("origin").setRemoteBranchName("master").call();
            }
        }
        catch (GitAPIException e)
        {
            log.error(e.getMessage(), e);
        }
    }
}
